package com.jiuyuejiu.func_book;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.jiuyuejiu.R;
import com.jiuyuejiu.application.ConstValues;
import com.jiuyuejiu.base.BaseActivity;
import com.jiuyuejiu.db.table.LK_BOOK_M;
import com.jiuyuejiu.func_book.adapter.BookListAdapter;
import com.jiuyuejiu.func_book.adapter.BookPathAdapter;
import com.jiuyuejiu.func_book.domain.BookStc;
import com.jiuyuejiu.utils.ShanHaiUtil;
import com.kylin.core.alertview.AlertView;
import com.kylin.core.loader.LatteLoader;
import com.kylin.core.utils.flyn.Eyes;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.widget.AppCompatTextView;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;


public class BookListActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout backBtn;
    private RelativeLayout confirmBtn;
    private AppCompatTextView confirmTv;
    private AppCompatTextView backTv;
    private AppCompatTextView titleTv;

    // 获取从上一页传递过来的数据
    private String title;
    private String username;
    private String password;

    private ListView dataLv;
    private LinearLayout emptyLl;

    private List<LK_BOOK_M> bookLst;
    ArrayList<BookStc> dataLst = new ArrayList<>();

    private AlertView mAlertViewExt;


    MyHandler handler;

    /**
     * 接收子线程消息的 Handler
     */
    public class MyHandler extends Handler {

        // 软引用
        SoftReference<BookListActivity> fragmentRef;

        public MyHandler(BookListActivity fragment) {
            fragmentRef = new SoftReference<BookListActivity>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            BookListActivity fragment = fragmentRef.get();
            if (fragment == null) {
                return;
            }

            Bundle bundle = msg.getData();
            super.handleMessage(msg);
            // 处理UI 变化
            switch (msg.what) {
                // 提示信息
                case ConstValues.WAIT0:
                    //
                    // fragment.getPicSuc(bundle);
                    break;
                case ConstValues.WAIT1:
                    // 关闭缓冲界面
                    // LatteLoader.stopLoading();
                    break;

                default:
                    break;
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_booklist);

        // 标题栏白底黑字
        Eyes.setStatusBarLightMode(this, Color.WHITE);

        // 接收传递过来的参数
        initCreate();
        // 初始化视图
        initView();
        // 初始化数据
        initData();
    }

    private void initCreate() {

        /*// 上一页面设置数据
        Intent intent = null;
        intent = new Intent(this, RePwdActivity.class);
        Bundle bundl = new Bundle();
        intent.putExtra("username", "");
        intent.putExtra("password", "");
        startActivity(intent);*/

        // 本页面获取数据
        Intent i = getIntent();
        username = (String) i.getSerializableExtra("username");
        password = (String) i.getSerializableExtra("password");
    }

    private void initView() {

        backBtn = (RelativeLayout) findViewById(R.id.top_navigation_rl_back);
        confirmBtn = (RelativeLayout) findViewById(R.id.top_navigation_rl_confirm);
        confirmTv = (AppCompatTextView) findViewById(R.id.top_navigation_bt_confirm);
        backTv = (AppCompatTextView) findViewById(R.id.top_navigation_bt_back);
        titleTv = (AppCompatTextView) findViewById(R.id.top_navigation_tv_title);
        confirmBtn.setVisibility(View.VISIBLE);
        confirmBtn.setOnClickListener(this);
        backBtn.setOnClickListener(this);

        emptyLl = (LinearLayout) findViewById(R.id.booklist_ll_empty);
        dataLv = (ListView) findViewById(R.id.booklist_ll_list);

    }

    private void initData() {
        handler = new MyHandler(this);
        // 获取上一页传递过来的数据
        Intent i = getIntent();
        title = i.getStringExtra("title");

        titleTv.setText(title);

        confirmTv.setText("路径");
        confirmTv.setTextSize(14);
        confirmTv.setTextColor(getResources().getColor(R.color.color_1DB974));

        dataLv.setEmptyView(emptyLl);


        // 初始化所有book
        initBookLst();
    }


    // 初始化所有book
    private void initBookLst() {

        LatteLoader.showLoading(BookListActivity.this);
        bookLst = new ArrayList<>();

        // 获取所有的图片类型
        BmobQuery<LK_BOOK_M> categoryBmobQuery = new BmobQuery<>();
        // categoryBmobQuery.addWhereEqualTo("pictype", pictype);

        String serviceip = ShanHaiUtil.getHttpid();

        // Mac 只获取pictype等于Mac的
        // categoryBmobQuery.addWhereEqualTo("booktype", "Mac");
        // Home 只获取pictype不等于Mac的
        categoryBmobQuery.addWhereNotEqualTo("booktype", "Mac");

        categoryBmobQuery.setLimit(500); // 最多500条数据 设置大于500也只显示500条
        categoryBmobQuery.findObjects(new FindListener<LK_BOOK_M>() {
            @Override
            public void done(List<LK_BOOK_M> object, BmobException e) {
                LatteLoader.stopLoading();
                if (e == null) {// 查询成功

                    bookLst.clear();
                    bookLst.addAll(object);


                    // 设置默认选择的类型
                    if (bookLst != null && bookLst.size() > 0) {

                        dataLst.clear();
                        for (LK_BOOK_M lk_book_m : bookLst) {
                            String path = lk_book_m.getBookpath();
                            String bookname = lk_book_m.getBookname();

                            // 传入字符串 将字符串分割成数组
                            String[] read = ShanHaiUtil.splitStringToArray(bookname);

                            BookStc bookStc;
                            for (String name : read) {
                                bookStc = new BookStc();
                                bookStc.setBookurl(path + name);
                                bookStc.setBookname(name);
                                dataLst.add(bookStc);
                            }
                        }


                        BookListAdapter picListAdapter = new BookListAdapter(BookListActivity.this, dataLst);
                        dataLv.setAdapter(picListAdapter);

                    }

                } else {// 查询成功
                    Toast.makeText(BookListActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 点击查看
        dataLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

                BookStc book = dataLst.get(position);

                // 打开webview
                Intent ni = new Intent(BookListActivity.this, BookDetailActivity.class);
                ni.putExtra("weburl", ConstValues.BOOKIP + book.getBookurl());//
                startActivity(ni);

            }
        });
    }


    // 选择bookpath
    private void selectBookpath(final List<LK_BOOK_M> pictypeList, String pictype) {

        mAlertViewExt = new AlertView("请选择路径", null, null, null, null, BookListActivity.this, AlertView.Style.Alert, null);
        ViewGroup extView = (ViewGroup) LayoutInflater.from(BookListActivity.this).inflate(R.layout.dialog_pic_type, null);
        ListView listview = (ListView) extView.findViewById(R.id.item_pic_type_lv_list);
        BookPathAdapter keyValueAdapter = new BookPathAdapter(BookListActivity.this, pictypeList,
                new String[]{"bookpath", "bookpath"}, pictype);
        listview.setAdapter(keyValueAdapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String selectbookpath = pictypeList.get(position).getBookpath();
                confirmTv.setText(selectbookpath.replace("/", ""));
                confirmTv.setTag(selectbookpath);

                // 设置默认选择的类型
                if (bookLst != null && bookLst.size() > 0) {

                    dataLst.clear();

                    for (LK_BOOK_M lk_book_m : bookLst) {

                        String path = lk_book_m.getBookpath();
                        String titles = lk_book_m.getBookname();

                        if (path.contains(selectbookpath)) {
                            // 传入字符串 将字符串分割成数组
                            String[] titleLst = ShanHaiUtil.splitStringToArray(titles);

                            BookStc bookStc;
                            for (String title : titleLst) {
                                bookStc = new BookStc();
                                bookStc.setBookurl(path + title);
                                bookStc.setBookname(title);
                                dataLst.add(bookStc);
                            }
                        }
                    }

                    BookListAdapter picListAdapter = new BookListAdapter(BookListActivity.this, dataLst);
                    dataLv.setAdapter(picListAdapter);

                }

                mAlertViewExt.dismiss();
            }
        });
        mAlertViewExt.addExtView(extView);
        mAlertViewExt.setCancelable(true).setOnDismissListener(null);
        mAlertViewExt.show();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 返回
            case R.id.top_navigation_rl_back:
                this.finish();
                break;
            case R.id.top_navigation_rl_confirm://
                selectBookpath(bookLst, (String) confirmTv.getTag());
                break;
        }
    }

    @Override
    public void onBackPressedSupport() {
        // 对于 4个类别的主Fragment内的回退back逻辑,已经在其onBackPressedSupport里各自处理了
        super.onBackPressedSupport();
        this.finish();
    }
}
